package cn.starrysky108.simpleerp;


import cn.starrysky108.simpleerp.article.entity.Article;
import cn.starrysky108.simpleerp.article.service.ArticleService;
import cn.starrysky108.simpleerp.core.util.JwtUtil;
import cn.starrysky108.simpleerp.core.util.SpringContextUtil;
import cn.starrysky108.simpleerp.pub.mapper.DataBaseManagerMapper;
import cn.starrysky108.simpleerp.system.entity.SystemPermission;
import cn.starrysky108.simpleerp.system.entity.SystemRole;
import cn.starrysky108.simpleerp.system.entity.SystemRolePermission;
import cn.starrysky108.simpleerp.system.entity.SystemRoleUser;
import cn.starrysky108.simpleerp.system.service.SystemPermissionService;
import cn.starrysky108.simpleerp.system.service.SystemRolePermissionService;
import cn.starrysky108.simpleerp.system.service.SystemRoleService;
import cn.starrysky108.simpleerp.system.service.SystemRoleUserService;
import cn.starrysky108.simpleerp.user.entity.User;
import cn.starrysky108.simpleerp.user.service.UserService;
import org.apache.commons.lang3.RandomUtils;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @author Carl Lee
 * @date 2021/7/21
 */
@SpringBootTest
public class InitData {
    @Autowired
    DataBaseManagerMapper mapper;
    Random random = new Random(100);

    /**
     * 初始化数据库
     */
    @Test
    @Rollback(false)
    void initDatabase() {
        //清空表
        mapper.listTableName().forEach(mapper::deleteTableData);
        initUser();
        initArticle();
        initSystemPermission();
        initSystemRole();
        initSystemRolePermission();
        initSystemRoleUser();
    }

    /**
     * 初始化user表数据
     */
    void initUser() {
        UserService userService = SpringContextUtil.getBean(UserService.class);
        List<User> users = new ArrayList<>(6);
        String pwd;
        //对原始密码进行加密
//        users.add(User.builder().username("test").password(pwd).build());
        for (int i = 0; i < 7; i++) {
            pwd = JwtUtil.encryptPassword("user" + i);
            User user = User.builder()
                    .username("user" + i)
                    .password(pwd)
                    .build();
            users.add(user);
        }
        userService.saveBatch(users);
    }

    /**
     * 初始化role表数据
     */
    void initSystemRole() {
        SystemRoleService roleService = SpringContextUtil.getBean(SystemRoleService.class);
        List<SystemRole> roles = new ArrayList<>(7);
        roles.add(SystemRole.builder().name("root").description("超级管理员").orderNum(999).build());
        roles.add(SystemRole.builder().name("admin").description("管理员").orderNum(999).build());
        roles.add(SystemRole.builder().name("guest").description("访客").orderNum(0).build());
        roles.add(SystemRole.builder().name("sales_manager").description("销售经理").orderNum(9).build());
        roles.add(SystemRole.builder().name("salesman").description("销售员").orderNum(1).build());
        roles.add(SystemRole.builder().name("warehouse_admin").description("仓库管理员").orderNum(19).build());
        roles.add(SystemRole.builder().name("warehouse_worker").description("仓库工作人员").orderNum(11).build());
        roleService.saveBatch(roles);
    }

    /**
     * 初始化permission表数据
     */
    void initSystemPermission() {
        SystemPermissionService permissionService = SpringContextUtil.getBean(SystemPermissionService.class);
        List<SystemPermission> perms = new ArrayList<>(6);
        perms.add(SystemPermission.builder().url("/user/**").name("用户操作").perms("/rest[user]").description("").orderNum(999).build());
        perms.add(SystemPermission.builder().url("/article/**").name("文章操作").perms("/rest[article]").description("").orderNum(999).build());
        perms.add(SystemPermission.builder().url("/sales/**").name("销售相关操作").perms("/rest[sales]").description("").orderNum(999).build());
        perms.add(SystemPermission.builder().url("/finance/**").name("金融操作").perms("/rest[finance]").description("").orderNum(999).build());
        perms.add(SystemPermission.builder().url("/product/**").name("产品操作").perms("/rest[product]").description("").orderNum(999).build());
        perms.add(SystemPermission.builder().url("/store/**").name("系统操作").perms("/rest[store]").description("").orderNum(999).build());
        perms.add(SystemPermission.builder().url("/purchase/**").name("采购操作").perms("/rest[purchase]").description("").orderNum(999).build());

        permissionService.saveBatch(perms);
    }

    /**
     * 初始化system_role_user表数据，每一个用户添加两个角色
     */
    void initSystemRoleUser() {
        SystemRoleUserService userSystemRoleService = SpringContextUtil.getBean(SystemRoleUserService.class);
        List<Map<String, Object>> users = mapper.listAll("user");
        List<Map<String, Object>> roles = mapper.listAll("system_role");
        List<SystemRoleUser> userSystemRoles = new ArrayList<>();
        for (Map<String, Object> user : users) {
            int j = RandomUtils.nextInt(0, roles.size());
            SystemRoleUser userSystemRole = SystemRoleUser.builder()
                    .roleId((Long) roles.get(j).get("id"))
                    .userId((Long) user.get("id"))
                    .build();
            userSystemRoles.add(userSystemRole);
            int k = RandomUtils.nextInt(0, roles.size());
            SystemRoleUser userSystemRole2 = SystemRoleUser.builder()
                    .roleId((Long) roles.get(j != k ? k : RandomUtils.nextInt(0, roles.size())).get("id"))
                    .userId((Long) user.get("id"))
                    .build();
            userSystemRoles.add(userSystemRole2);
        }
        userSystemRoleService.saveBatch(userSystemRoles);
    }

    /**
     * 初始化system_role_permission表数据
     */
    void initSystemRolePermission() {
        SystemRolePermissionService rolePermissionService = SpringContextUtil.getBean(SystemRolePermissionService.class);
        List<Map<String, Object>> perms = mapper.listAll("system_permission");
        List<Map<String, Object>> roles = mapper.listAll("system_role");
        List<SystemRolePermission> systemRolePermissions = new ArrayList<>();

        for (int i = 0; i < roles.size(); i++) {
            SystemRolePermission rolePermission = SystemRolePermission.builder()
                    .roleId((Long) roles.get(i).get("id"))
                    .permissionId((Long) perms.get(i).get("id"))
                    .build();
            systemRolePermissions.add(rolePermission);
        }
        rolePermissionService.saveBatch(systemRolePermissions);
    }

    /**
     * 初始化article表数据
     */
    void initArticle() {
        ArticleService articleService = SpringContextUtil.getBean(ArticleService.class);
        List<Article> articles = new ArrayList<>();
        List<Map<String, Object>> users = mapper.listAll("user");
        for (int i = 0; i < 5; i++) {
            int j = random.nextInt(users.size() + 1);
            Article article = Article.builder()
                    .title("标题" + i)
                    .author((Long) users.get(j).get("id"))
                    .content("内容" + i)
                    .build();
            articles.add(article);
        }
        articleService.saveBatch(articles);
    }
}